package com.ruoyi.quartz.task;

import cn.hutool.extra.qrcode.BufferedImageLuminanceSource;
import cn.hutool.log.Log;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.zxing.*;
import com.google.zxing.common.HybridBinarizer;
import com.ruoyi.business.domain.*;
import com.ruoyi.business.param.MsgPayResult;
import com.ruoyi.business.response.ResponseData;
import com.ruoyi.business.service.*;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.*;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.redis.RedisUtil;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 定时任务调度测试
 * 
 * @author admin
 */
@Component("smjmsSMOrderCheckTask")
public class SmjmsSMOrderCheckTask
{
    @Resource
    private ITOrderInfoService orderService;
    @Resource
    private ITRecipientInfoService userRecipientService;
    @Resource
    private ChargeService chargeService;
    @Resource
    private LoginService loginService;
    private Log logger = Log.get();

    @Autowired
    private ITSmjGoodListService itSmjGoodListService;

    @Autowired
    private ITSmjMachineListService itSmjMachineListService;

    @Autowired
    private ITSmjOrderInfoService itSmjOrderInfoService;

    @Autowired
    private RedisUtil redisUtil;
    /**
     * 检查支付超时的订单。状态为待支付并且当前时间已经超过有效时间
     */
    public void checkOrder() throws Exception {
//        logger.info("CXZF订单查询..");

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            TOrderInfo query = new TOrderInfo();
//        query.setChannelType("alipay");
            query.setChannel("smj_sm");
            query.setStatus(1);
            String newdateTime = DateUtils.dealDate("10分钟前");
//        String dateTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
            query.getParams().put("beginCreateTime", newdateTime);
            List<TOrderInfo> orderInfos = orderService.selectTOrderInfoListByNoAuth(query);
            for (TOrderInfo orderInfo : orderInfos) {
                synchronized (this) {
                if (orderInfo.getValidTime().before(new Date())) {
                    continue;
                }
                TSmjGoodList tSmjGoodList = itSmjGoodListService.selectTSmjGoodListById(Long.valueOf(orderInfo.getQrcodeTxt()));
                if (tSmjGoodList == null) {
                    continue;
                }
                TRecipientInfo userRecipientInfo = userRecipientService.selectTRecipientInfoById(orderInfo.getRecipientId());
                String accountJson = userRecipientInfo.getAccountJson();
                JSONObject accountObj = JSONObject.parseObject(accountJson);
                String[] loginUrls = accountObj.getString("loginUrl").split("login.html");
                HashMap<String, String> headerMap = new HashMap();
                headerMap.put("Cookie", accountObj.getString("cookie"));
                headerMap.put("User-Agent", accountObj.getString("User-Agent"));
                LocalDate now = LocalDate.now();
                String logingType = accountObj.getString("logingType");
                if (StringUtils.isBlank(logingType)) {
                    logingType = "pc";
                }
                logger.info("查单类型：{}", logingType);
                HashMap<String, String> requestMap = new HashMap();
                if (logingType.equals("mobile")) {
                    String mobileOrderUrl = loginUrls[0] + "mobile/salesAll.html?startTime=" + now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")) + "&endTime=" + now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")) + "&pageType=4";
                    HttpResponse mobilehttpResponse = HttpUtils.httpFormPost(mobileOrderUrl, headerMap, accountObj.getString("cookie"), requestMap, "", "");
                    if (mobilehttpResponse.getBody().equals("") || mobilehttpResponse.getBody().contains("登录")) {
                        logger.info("未登录重新登录查询订单");
                        userRecipientInfo = reLogin(userRecipientInfo);
                        mobilehttpResponse = rePaydetail(userRecipientInfo, orderInfo);
                    }
                    Document mobileDoc = mobilehttpResponse.getDocument();
                    Elements listItems = mobileDoc.getElementsByClass("list-item");
                    for (int i = 0; i < listItems.size(); i++) {
                        Element middle = listItems.get(i).getElementsByClass("middle").first();
                        Elements rows = middle.getElementsByClass("row");
                        Date payTime = sdf.parse(rows.get(3).getElementsByClass("value").first().text());
                        String price = listItems.get(i).getElementsByClass("price").first().text();
                        String hd = listItems.get(i).getElementsByClass("huodao").first().text();
                        String payType = listItems.get(i).getElementsByClass("pay-way").first().text();

                        String machineName = rows.get(0).getElementsByClass("value").first().text();
                        String orderId = rows.get(1).getElementsByClass("value").first().text();
                        logger.info("机器名称：{},货道:{},金额：{}，支付时间：{}", rows.get(0).getElementsByClass("value").first().text(), hd, price, rows.get(3).getElementsByClass("value").first().text());
                        TSmjOrderInfo tSmjOrderInfo = new TSmjOrderInfo();
                        tSmjOrderInfo.setRealChanleOrderNo(orderId);
                        tSmjOrderInfo.setMachineName(machineName);
                        tSmjOrderInfo.setHdCode(hd);
                        tSmjOrderInfo.setPayAmount(price);
                        tSmjOrderInfo.setPayTime(payTime);
                        tSmjOrderInfo.setPayType(payType);
                        tSmjOrderInfo.setUserId(userRecipientInfo.getUserId());
                        List<TSmjOrderInfo> tSmjOrderInfoList = itSmjOrderInfoService.selectTSmjOrderInfoListByNoAuth(tSmjOrderInfo);
                        if (tSmjOrderInfoList.size() == 0) {
                            tSmjOrderInfo.setStatus(0);
                            itSmjOrderInfoService.insertTSmjOrderInfo(tSmjOrderInfo);
                        }else{
                            tSmjOrderInfo = tSmjOrderInfoList.get(0);
                        }
                        boolean flag = false;
                        if (payTime.after(orderInfo.getUpdateTime()) && payTime.before(orderInfo.getValidTime())) {
                            logger.info("订单修改时间：{},订单支付时间:{},订单失效时间：{}", sdf.format(orderInfo.getUpdateTime()), rows.get(3).getElementsByClass("value").first().text(), sdf.format(orderInfo.getValidTime()));
                            flag = true;
                        }
                        BigDecimal payAmount = new BigDecimal(orderInfo.getMoney() / 100).setScale(2);

                        if (machineName.equals(orderInfo.getQrcodeContent()) && hd.equals(tSmjGoodList.getGoodHd()) && new BigDecimal(price).compareTo(payAmount) == 0 && flag) {
                            TOrderInfo queryOrder = new TOrderInfo();
                            queryOrder.setChannel(orderInfo.getChannel());
                            queryOrder.setPay3rdOrderNo(orderId);
                            String dateTime = new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + " 00:00:00";
                            queryOrder.getParams().put("beginCreateTime", dateTime);
                            List<TOrderInfo> doneTPaymentOrderList = orderService.selectTOrderInfoListByNoAuth(queryOrder);
                            logger.info("渠道订单号是否已经被用：{}", doneTPaymentOrderList.size());
                            if (doneTPaymentOrderList.size() > 0) {
                                continue;
                            }
                            tSmjGoodList.setGoodStatus(0);
                            tSmjGoodList.setGoodNum(tSmjGoodList.getGoodNum() - 1);
                            TSmjGoodList queryTsmj = new TSmjGoodList();
                            queryTsmj.setMachineId(tSmjGoodList.getMachineId());
                            queryTsmj.setSmGoodId(tSmjGoodList.getSmGoodId());
                            if (tSmjGoodList.getPayType().equals("ALI")) {
                                queryTsmj.setPayType("WX");
                            } else {
                                queryTsmj.setPayType("ALI");
                            }
                            List<TSmjGoodList> tmpList = itSmjGoodListService.selectTSmjGoodListListByNoAuth(queryTsmj);
                            TSmjGoodList tmp = null;
                            if (tmpList.size() > 0) {
                                tmp = tmpList.get(0);
                                tmp.setGoodNum(tSmjGoodList.getGoodNum());
                                itSmjGoodListService.updateTSmjGoodList(tmp);
                            }
                            logger.info("商品剩余数量：{}", tSmjGoodList.getGoodNum()-1 );
                            if ((tSmjGoodList.getGoodNum() - 1) < 5) {
                                TSmjMachineList tSmjMachineList = itSmjMachineListService.selectTSmjMachineListById(tSmjGoodList.getMachineId());
                                requestMap = new HashMap();
                                requestMap.put("id", tSmjMachineList.getSmMachineId());
                                JSONArray jsonArray = new JSONArray();
                                JSONObject obj = new JSONObject();
                                obj.put("id", tSmjGoodList.getSmGoodId());
                                obj.put("huodao", tSmjGoodList.getGoodHd().replace("货道", ""));
                                obj.put("stock", "255");
                                obj.put("price", tSmjGoodList.getGoodPrice().setScale(2));
                                jsonArray.add(obj);
                                requestMap.put("array", jsonArray.toJSONString());
                                String bhUrl = loginUrls[0] + "operator/submitGoodsSetting.action";
                                logger.info("补货参数：{}", JSON.toJSONString(requestMap));
                                HttpResponse bhhttpResponse = HttpUtils.httpFormPost(bhUrl, headerMap, accountObj.getString("cookie"), requestMap, "", "");
                                logger.info("补货返回：{}", bhhttpResponse.getBody());
                                tmp.setGoodNum(255L);
                                itSmjGoodListService.updateTSmjGoodList(tmp);
                                tSmjGoodList.setGoodNum(255L);
                            }
                            itSmjGoodListService.updateTSmjGoodList(tSmjGoodList);
                            tSmjOrderInfo = itSmjOrderInfoService.selectTSmjOrderInfoById(tSmjOrderInfo.getId());
                            tSmjOrderInfo.setStatus(1);
                            tSmjOrderInfo.setOrderCode(orderInfo.getId().toString());
                            tSmjOrderInfo.setMerOrderNo(orderInfo.getOutTradeNo());
                            tSmjOrderInfo.setCustomOrderNo(orderInfo.getCustomOrderNo());
                            itSmjOrderInfoService.updateTSmjOrderInfo(tSmjOrderInfo);
                            MsgPayResult msgPayResult = new MsgPayResult();
                            msgPayResult.setChannel(orderInfo.getChannel());
                            msgPayResult.setTradeNo(orderInfo.getId().toString());
                            msgPayResult.setChannelAccount(userRecipientInfo.getChannelAccount());
                            msgPayResult.setOrderId(orderId);
                            msgPayResult.setRealMoney(MoneyUtil.fenToYuan(orderInfo.getMoney() + ""));
                            msgPayResult.setUid(userRecipientInfo.getUserId().toString());
                            msgPayResult.setBillTime(rows.get(3).getElementsByClass("value").first().text());

                            msgPayResult.setChannelPayMsgResult(listItems.get(i).toString());
                            ResponseData responseData = chargeService.updateOrderPayResult(false, orderInfo.getId(), msgPayResult, false);
                            chargeService.notifyUserPaySucc(orderInfo.getId());

                            logger.info("售货机订单回调..订单号：" + orderInfo.getId() + " 金额：" + orderInfo.getMoney() + " 处理结果：{}", responseData.getSuccess());
                        }
                    }
                } else {
                    String orderUrl = loginUrls[0] + "operator/paydetail.html";

                    requestMap.put("startTime", now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")) + " 00:00");
                    LocalDate tomorrow = now.plusDays(1);
                    requestMap.put("endTime", tomorrow.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")) + " 00:00:00");
                    requestMap.put("status", "1");
                    requestMap.put("hasRefund", "5");
                    if (orderInfo.getChannel().contains("alipay_")) {
                        requestMap.put("payType", "3");
                    } else {
                        requestMap.put("payType", "4");
                    }
                    requestMap.put("roleType", "10");
                    logger.info("查单参数：{}", JSON.toJSONString(requestMap));
                    HttpResponse httpResponse = HttpUtils.httpFormPost(orderUrl, headerMap, accountObj.getString("cookie"), requestMap, "", "");
//                logger.info("查单返回：{}",httpResponse.getBody());
                    if (httpResponse.getBody().contains("登录")) {
                        logger.info("未登录重新登录查询订单");
                        userRecipientInfo = reLogin(userRecipientInfo);
                        httpResponse = rePaydetail(userRecipientInfo, orderInfo);
                    }
                    Document document = httpResponse.getDocument();
                    Elements lielements = document.select("tbody");
                    Elements trs = lielements.first().select("tr");
                    /**
                     * <tr class="am-active">
                     * 					<td>合计</td>
                     * 					<td colspan="20">
                     * 					销售总量：2544个，销量总额：375710.0元，
                     * 					其中支付宝：375710.0元，支付宝刷脸：0.0元，
                     * 					微信：0.0元，微信刷脸：0.0元，
                     * 					微信刷掌：0.0元，
                     * 					微信会员：0.0元，IC卡：0.0元，
                     * 					扶贫：0.0元，GHL：0.0元，
                     * 					成本：271408.0元，利润：104302.00元，
                     * 					此处金额不包含支付渠道手续费，手续费按实际费率为准。
                     * 					</td>
                     * 				</tr>
                     */
                    //销售总量：2600个，销量总额：383110.0元，其中支付宝：383110.0元，支付宝刷脸：0.0元，微信：0.0元，微信刷脸：0.0元，微信刷掌：0.0元，微信会员：0.0元，IC卡：0.0元，扶贫：0.0元，GHL：0.0元，成本：276461.0元，利润：106649.00元，此处金额不包含支付渠道手续费，手续费按实际费率为准。
                    Element lasttd = trs.get(trs.size() - 1).select("td").get(1);
                    String statics = lasttd.text().replace(" ", "");
                    logger.info(statics);
                    //long totalNum = Long.valueOf(statics.split("个，销量总额：")[0].split("销售总量：")[1]);
                    for (int i = 0; i < trs.size() - 1; i++) {
                        Element tr = trs.get(i);
                        Elements cells = tr.select("td");
                        Date payTime = sdf.parse(cells.get(13).text());
                        logger.info("机器名称：{},货道:{},金额：{}，支付时间：{}", cells.get(4).text(), cells.get(5).text(), cells.get(19).text(), cells.get(13).text());
                        TSmjOrderInfo tSmjOrderInfo = new TSmjOrderInfo();
                        tSmjOrderInfo.setRealChanleOrderNo(cells.get(2).text());
                        tSmjOrderInfo.setMachineName(cells.get(4).text());
                        tSmjOrderInfo.setHdCode(cells.get(5).text());
                        tSmjOrderInfo.setPayAmount(cells.get(19).text());
                        tSmjOrderInfo.setPayTime(payTime);
                        tSmjOrderInfo.setPayType(cells.get(8).text());
                        tSmjOrderInfo.setUserId(userRecipientInfo.getUserId());
                        List<TSmjOrderInfo> tSmjOrderInfoList = itSmjOrderInfoService.selectTSmjOrderInfoListByNoAuth(tSmjOrderInfo);

                        if (tSmjOrderInfoList.size() == 0) {
                            tSmjOrderInfo.setStatus(0);
                            itSmjOrderInfoService.insertTSmjOrderInfo(tSmjOrderInfo);
                        }else{
                            tSmjOrderInfo = tSmjOrderInfoList.get(0);
                        }
                        boolean flag = false;
                        if (payTime.after(orderInfo.getUpdateTime()) && payTime.before(orderInfo.getValidTime())) {
                            logger.info("订单修改时间：{},订单支付时间:{},订单失效时间：{}", sdf.format(orderInfo.getUpdateTime()), cells.get(13).text(), sdf.format(orderInfo.getValidTime()));
                            flag = true;
                        }
                        BigDecimal payAmount = new BigDecimal(orderInfo.getMoney() / 100).setScale(2);
                        if (cells.get(4).text().equals(orderInfo.getQrcodeContent()) && cells.get(5).text().equals(tSmjGoodList.getGoodHd()) && new BigDecimal(cells.get(19).text()).compareTo(payAmount) == 0 && flag) {
                            TOrderInfo queryOrder = new TOrderInfo();
                            queryOrder.setChannel(orderInfo.getChannel());
                            queryOrder.setPay3rdOrderNo(cells.get(2).text());
                            String dateTime = new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + " 00:00:00";
                            queryOrder.getParams().put("beginCreateTime", dateTime);
                            List<TOrderInfo> doneTPaymentOrderList = orderService.selectTOrderInfoListByNoAuth(queryOrder);
                            logger.info("渠道订单号是否已经被用：{}", doneTPaymentOrderList.size());
                            if (doneTPaymentOrderList.size() > 0) {
                                continue;
                            }
                            tSmjGoodList.setGoodStatus(0);
                            tSmjGoodList.setGoodNum(tSmjGoodList.getGoodNum() - 1);
                            TSmjGoodList queryTsmj = new TSmjGoodList();
                            queryTsmj.setMachineId(tSmjGoodList.getMachineId());
                            queryTsmj.setSmGoodId(tSmjGoodList.getSmGoodId());
                            if (tSmjGoodList.getPayType().equals("ALI")) {
                                queryTsmj.setPayType("WX");
                            } else {
                                queryTsmj.setPayType("ALI");
                            }
                            List<TSmjGoodList> tmpList = itSmjGoodListService.selectTSmjGoodListListByNoAuth(queryTsmj);
                            TSmjGoodList tmp = null;
                            if (tmpList.size() > 0) {
                                tmp = tmpList.get(0);
                                tmp.setGoodNum(tSmjGoodList.getGoodNum());
                                itSmjGoodListService.updateTSmjGoodList(tmp);
                            }
                            logger.info("商品剩余数量：{}", tSmjGoodList.getGoodNum()-1 );
                            if ((tSmjGoodList.getGoodNum() - 1) < 5) {
                                TSmjMachineList tSmjMachineList = itSmjMachineListService.selectTSmjMachineListById(tSmjGoodList.getMachineId());
                                requestMap = new HashMap();
                                requestMap.put("id", tSmjMachineList.getSmMachineId());
                                JSONArray jsonArray = new JSONArray();
                                JSONObject obj = new JSONObject();
                                obj.put("id", tSmjGoodList.getSmGoodId());
                                obj.put("huodao", tSmjGoodList.getGoodHd().replace("货道", ""));
                                obj.put("stock", "255");
                                obj.put("price", tSmjGoodList.getGoodPrice().setScale(2));
                                jsonArray.add(obj);
                                requestMap.put("array", jsonArray.toJSONString());
                                String bhUrl = loginUrls[0] + "operator/submitGoodsSetting.action";
                                logger.info("补货参数：{}", JSON.toJSONString(requestMap));
                                HttpResponse bhhttpResponse = HttpUtils.httpFormPost(bhUrl, headerMap, accountObj.getString("cookie"), requestMap, "", "");
                                logger.info("补货返回：{}", bhhttpResponse.getBody());
                                tmp.setGoodNum(255L);
                                itSmjGoodListService.updateTSmjGoodList(tmp);
                                tSmjGoodList.setGoodNum(255L);
                            }
                            itSmjGoodListService.updateTSmjGoodList(tSmjGoodList);
                            tSmjOrderInfo = itSmjOrderInfoService.selectTSmjOrderInfoById(tSmjOrderInfo.getId());
                            tSmjOrderInfo.setStatus(1);
                            tSmjOrderInfo.setOrderCode(orderInfo.getId().toString());
                            tSmjOrderInfo.setMerOrderNo(orderInfo.getOutTradeNo());
                            tSmjOrderInfo.setCustomOrderNo(orderInfo.getCustomOrderNo());
                            itSmjOrderInfoService.updateTSmjOrderInfo(tSmjOrderInfo);

                            MsgPayResult msgPayResult = new MsgPayResult();
                            msgPayResult.setChannel(orderInfo.getChannel());
                            msgPayResult.setTradeNo(orderInfo.getId().toString());
                            msgPayResult.setChannelAccount(userRecipientInfo.getChannelAccount());
                            msgPayResult.setOrderId(cells.get(2).text());
                            msgPayResult.setRealMoney(MoneyUtil.fenToYuan(orderInfo.getMoney() + ""));
                            msgPayResult.setUid(userRecipientInfo.getUserId().toString());
                            msgPayResult.setBillTime(cells.get(13).text());

                            msgPayResult.setChannelPayMsgResult(tr.toString());
                            ResponseData responseData = chargeService.updateOrderPayResult(false, orderInfo.getId(), msgPayResult, false);
                            chargeService.notifyUserPaySucc(orderInfo.getId());

                            logger.info("售货机订单回调..订单号：" + orderInfo.getId() + " 金额：" + orderInfo.getMoney() + " 处理结果：{}", responseData.getSuccess());
                        }
                    }
                }
            }
        }
    }


    private HttpResponse rePaydetail(TRecipientInfo tUserRecipientInfo,TOrderInfo orderInfo){
        String accountJson = tUserRecipientInfo.getAccountJson();
        JSONObject  accountObj = JSONObject.parseObject(accountJson);
        HashMap<String, String> requestMap = new HashMap();
        HashMap<String, String> headerMap = new HashMap();
        headerMap.put("Cookie",accountObj.getString("cookie"));
        headerMap.put("User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36");
        String[] loginUrls = accountObj.getString("loginUrl").split("login.html");
        String orderUrl = loginUrls[0]+"operator/paydetail.html";
        requestMap = new HashMap();
        LocalDate now = LocalDate.now();
        requestMap.put("startTime",now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))+" 00:00");
        LocalDate tomorrow = now.plusDays(1);
        requestMap.put("endTime",tomorrow.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))+" 00:00:00");
        requestMap.put("status","1");
        requestMap.put("hasRefund","5");
        if(orderInfo.getChannel().contains("alipay_")){
            requestMap.put("payType","3");
        }else{
            requestMap.put("payType","4");
        }
        requestMap.put("roleType","10");
        logger.info("查单参数：{}",JSON.toJSONString(requestMap));
        HttpResponse orderRes =HttpUtils.httpFormPost(orderUrl,headerMap,accountObj.getString("cookie"),requestMap,"","");
//        logger.info("查单返回：{}",httpResponse.getBody());
        return orderRes;
        //获取售货机列表

    }

    private TRecipientInfo reLogin(TRecipientInfo tUserRecipientInfo){
        String accountJson = tUserRecipientInfo.getAccountJson();
        JSONObject  accountObj = JSONObject.parseObject(accountJson);
        HashMap<String, String> headerMap = new HashMap();
        headerMap.put("User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36");
        logger.info("后台登录HTMLurl："+accountObj.getString("loginUrl"));
        HttpResponse httpResponse = HttpUtils.httpFormGet(accountObj.getString("loginUrl"),headerMap,"","售货机【盛马】","");
        String cookies = httpResponse.getCookie();
        headerMap.put("Cookie",cookies);
        logger.info("登录cookies：{}",cookies);
        accountObj.put("cookie",cookies);
        accountObj.put("User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36");
        HashMap<String, String> requestMap = new HashMap();
        requestMap.put("username",tUserRecipientInfo.getChannelAccount());
        requestMap.put("password",accountObj.getString("password"));
        String[] loginUrls = accountObj.getString("loginUrl").split("login.html");
        logger.info("登录地址：{},用户名：{},password:{}",loginUrls[0]+"user/login.action",tUserRecipientInfo.getChannelAccount(),accountObj.getString("password"));
        HttpResponse b =  HttpUtils.httpFormPost(loginUrls[0]+"user/login.action",headerMap,cookies,requestMap,"售货机【盛马】","");
        tUserRecipientInfo.setAccountJson(accountObj.toJSONString());
        userRecipientService.updateTRecipientInfo(tUserRecipientInfo);
        return tUserRecipientInfo;
    }

    private String timeStamp2Date(String str_num) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//要转换的时间格式
        if (str_num.length() == 13) {
            String date = sdf.format(new Date(Long.parseLong(str_num)));
            return date;
        } else {
            String date = sdf.format(new Date(Integer.parseInt(str_num) * 1000L));
            return date;
        }
    }

    public void delSmjSmOrder(){
        TSmjOrderInfo query = new TSmjOrderInfo();
        String dateTime = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        query.getParams().put("beginCreateTime",dateTime+" 00:00:00");
        itSmjOrderInfoService.deleteTSmjOrderInfo(query);
    }

    public void anyscGoods()
    {
        TSmjMachineList query = new TSmjMachineList();
        query.setMachineType("SHENGMA");
        List<TSmjMachineList> tSmjMachineLists = itSmjMachineListService.selectTSmjMachineListListByNoAuth(query);
        for(TSmjMachineList tSmjMachineList : tSmjMachineLists){
            TRecipientInfo tUserRecipientInfo = userRecipientService.selectTRecipientInfoById(tSmjMachineList.getUserRecipientId());
//        TRealChannelConfig tRealChannelConfig = tRealChannelConfigMapper.selectTRealChannelConfigByRealChannelCode(tSmjMachineList.getRealChannelCode());
//        JSONObject rsCfgObj = JSONObject.parseObject(tRealChannelConfig.getReturnParamCfg());
//        JSONObject reqObj = JSONObject.parseObject(tRealChannelConfig.getRequestParam());
            String accountJson = tUserRecipientInfo.getAccountJson();
            JSONObject accountObj = JSONObject.parseObject(accountJson);
            String[] loginUrls = accountObj.getString("loginUrl").split("login.html");
            HashMap<String, String> headerMap = new HashMap();
            HashMap<String, String> dataMap = new HashMap();
            headerMap.put("Cookie",accountObj.getString("cookie"));
            headerMap.put("User-Agent","Nebula AlipayDefined(nt:WIFI,ws:360|0|3.0) AliApp(AP/10.0.18.062203) AlipayClient/10.0.18.062203 Language/zh-Hans useStatusBar/true");
//        String url = tSmjMachineList.getMachineGoodUrl();
//        logger.info("货品HTMLurl："+url);
//        HttpResponse httpResponse = HttpUtils.httpFormGet(url,headerMap,"","售货机","");
//        logger.info("返回的HTML:"+httpResponse.getDocument().text());
            logger.info("商品总码HTMLurl："+loginUrls[0]+"qrcode.html?mid="+tSmjMachineList.getSmMachineId());
            HttpResponse qrcodeRes = HttpUtils.httpFormGet(loginUrls[0]+"qrcode.html?mid="+tSmjMachineList.getSmMachineId(),headerMap,"","");
            Document qrcodedocument = qrcodeRes.getDocument();
            Element imgEle = qrcodedocument.getElementsByTag("img").first();
            String imgDownloadUrl = imgEle.attr("src");
            String filePath = RuoYiConfig.getUploadPath();
            logger.info("保存地址：{}",filePath+"/"+tSmjMachineList.getMachineName()+".png");
            FileUtils.downloadByCommonIO(imgDownloadUrl,filePath,tSmjMachineList.getMachineName()+".png");
            String spzmhref = decodeQR(filePath+"/"+tSmjMachineList.getMachineName()+".png");
            HttpResponse spzmhttpResponse = HttpUtils.httpFormGet(spzmhref,headerMap,"","售货机","");
            Document szpzDoc= spzmhttpResponse.getDocument();
            Elements szpzEles =  szpzDoc.select("li");
            JSONObject spObj = new JSONObject();
            for (int i = 0; i < szpzEles.size(); i++) {
                String goodUrl = szpzEles.get(i).select("a").first().attr("href");
                String hd  = szpzEles.get(i).select("a").first().select("span").first().text();
                spObj.put(hd,goodUrl);
            }
            if(szpzEles.size()==0){
                logger.info("未查询到商品总信息删除售卖机货物信息："+tSmjMachineList.getMachineName());
                itSmjGoodListService.deleteTSmjGoodListByMachineId(tSmjMachineList.getId());
                continue;
            }
            logger.info("商品总信息："+spObj);
            logger.info("后台货品HTMLurl："+loginUrls[0]+"operator/huodao.html?id="+tSmjMachineList.getSmMachineId());
            HttpResponse adhttpResponse = HttpUtils.httpFormGet(loginUrls[0]+"operator/huodao.html?id="+tSmjMachineList.getSmMachineId(),headerMap,"","售货机","");
            if(adhttpResponse.getBody().contains("登录")){
                reLogin(tUserRecipientInfo);
                adhttpResponse= HttpUtils.httpFormGet(loginUrls[0]+"operator/huodao.html?id="+tSmjMachineList.getSmMachineId(),headerMap,"","售货机","");
            }
            Document addocument = adhttpResponse.getDocument();
            Element divele =  addocument.getElementById("content");
            Elements tbody = divele.select("tbody");
            Elements trs = tbody.first().select("tr");
            JSONObject trObj = new JSONObject();
            for (int i = 0; i < trs.size(); i++) {
                Element tr = trs.get(i);
                Elements cells = tr.select("td");
                Element checkboxe = cells.get(0).select("input[type=checkbox]").first();
                trObj.put(cells.get(1).text(),checkboxe.val()+"#"+cells.get(5).text());
                TSmjGoodList tSmjGoodList = new TSmjGoodList();
                tSmjGoodList.setMachineId(tSmjMachineList.getId());
                tSmjGoodList.setMachineType(tSmjMachineList.getMachineType());
                String hd = cells.get(1).text();
                tSmjGoodList.setGoodHd(hd);
                tSmjGoodList.setPayType("ALI");
                tSmjGoodList.setRealChannelCode("alipay_smj_sm_h5");
                List<TSmjGoodList> tSmjGoodLists =  itSmjGoodListService.selectTSmjGoodListListByNoAuth(tSmjGoodList);
                if(tSmjGoodLists.size()>0){
                    tSmjGoodList = tSmjGoodLists.get(0);
                }
                tSmjGoodList.setUserId(tUserRecipientInfo.getUserId());
                //获取商品链接
                String href = spObj.getString(hd);
                if(StringUtils.isBlank(href)){
                    tSmjGoodList.setGoodStatus(1);
                    itSmjGoodListService.updateTSmjGoodList(tSmjGoodList);
                    continue;
                }
                tSmjGoodList.setGoodUrl(href.replace("payInfo.html","payInfo_alipay.html"));
                String goodName = cells.get(3).text();
                tSmjGoodList.setGoodName(goodName);
                tSmjGoodList.setSmGoodId(trObj.getString(hd).split("#")[0]);
                tSmjGoodList.setGoodNum(Long.valueOf(trObj.getString(hd).split("#")[1]));
                String price =cells.get(6).text();
                tSmjGoodList.setGoodPrice(new BigDecimal(price.replace("￥","")).setScale(2));
                if(tSmjGoodLists.size()>0){
                    tSmjGoodList.setUpdateTime(new Date());
                    itSmjGoodListService.updateTSmjGoodList(tSmjGoodList);
                }else {
                    tSmjGoodList.setGoodStatus(0);
                    itSmjGoodListService.insertTSmjGoodList(tSmjGoodList);
                }
                tSmjGoodList = new TSmjGoodList();
                tSmjGoodList.setMachineId(tSmjMachineList.getId());
                tSmjGoodList.setGoodHd(hd);
                tSmjGoodList.setRealChannelCode("wechat_smj_sm_h5");
                tSmjGoodList.setPayType("WX");
                tSmjGoodList.setMachineType(tSmjMachineList.getMachineType());
                tSmjGoodLists =  itSmjGoodListService.selectTSmjGoodListListByNoAuth(tSmjGoodList);
                if(tSmjGoodLists.size()>0){
                    tSmjGoodList = tSmjGoodLists.get(0);
                }
                tSmjGoodList.setUserId(tUserRecipientInfo.getUserId());
                tSmjGoodList.setGoodUrl(href);
                tSmjGoodList.setGoodName(goodName);
                tSmjGoodList.setSmGoodId(trObj.getString(hd).split("#")[0]);
                tSmjGoodList.setGoodNum(Long.valueOf(trObj.getString(hd).split("#")[1]));
                tSmjGoodList.setGoodPrice(new BigDecimal(price.replace("￥","")).setScale(2));
                if(tSmjGoodLists.size()>0){
                    tSmjGoodList.setUpdateTime(new Date());
                    itSmjGoodListService.updateTSmjGoodList(tSmjGoodList);
                }else {
                    tSmjGoodList.setGoodStatus(0);
                    itSmjGoodListService.insertTSmjGoodList(tSmjGoodList);
                }
                //刪除redis緩存
                logger.info("盛马删除缓存KEY:{}","PLATFORM_SMJSMALI"+tUserRecipientInfo.getId()+tSmjGoodList.getGoodPrice());
//                redisUtil.remove("PLATFORM_SMJSMALI"+tUserRecipientInfo.getId()+tSmjGoodList.getGoodPrice());
//                redisUtil.remove("PLATFORM_SMJSMWX"+tUserRecipientInfo.getId()+tSmjGoodList.getGoodPrice());
            }
            redisUtil.removePattern("PLATFORM_SMJSMALI*");
            redisUtil.removePattern("PLATFORM_SMJSMWX*");
            tSmjMachineList.setUpdateTime(DateUtils.getNowDate());
            itSmjMachineListService.updateTSmjMachineList(tSmjMachineList);
        }

    }

    private String  decodeQR(String filePath) {
//        String filePath = "E:/txdata/data/images/qrCode.jpg";//二维码路径
        BufferedImage image;
        Result result = null;
        try {
            image = ImageIO.read(new File(filePath));
            LuminanceSource source = new BufferedImageLuminanceSource(image);
            Binarizer binarizer = new HybridBinarizer(source);
            BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
            Map<DecodeHintType, Object> hints = new HashMap<DecodeHintType, Object>();
            hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
            result = new MultiFormatReader().decode(binaryBitmap, hints);// 对图像进行解码
            logger.info("图片中内容：  ");
            logger.info("author： " + result.getText());
            logger.info("图片中格式：  ");
            logger.info("encode： " + result.getBarcodeFormat());
            return result.getText();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }


    public void checkOrderByDeliveryAndRefund() throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        TOrderInfo query = new TOrderInfo();
//        query.setChannelType("alipay");
        query.setChannel("smj_sm");
        query.setStatus(1);
        String newdateTime = DateUtils.dealDate("10分钟前");
//        String dateTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        query.getParams().put("beginCreateTime", newdateTime);
        List<TOrderInfo> orderInfos = orderService.selectTOrderInfoListByNoAuth(query);
        for (TOrderInfo orderInfo : orderInfos) {
            synchronized (this) {
                if (orderInfo.getValidTime().before(new Date())) {
                    continue;
                }
                TSmjGoodList tSmjGoodList = itSmjGoodListService.selectTSmjGoodListById(Long.valueOf(orderInfo.getQrcodeTxt()));
                if (tSmjGoodList == null) {
                    continue;
                }
                TRecipientInfo userRecipientInfo = userRecipientService.selectTRecipientInfoById(orderInfo.getRecipientId());
                String accountJson = userRecipientInfo.getAccountJson();
                JSONObject accountObj = JSONObject.parseObject(accountJson);
                String[] loginUrls = accountObj.getString("loginUrl").split("login.html");
                HashMap<String, String> headerMap = new HashMap();
                headerMap.put("Cookie", accountObj.getString("cookie"));
                headerMap.put("User-Agent", accountObj.getString("User-Agent"));
                BigDecimal payAmount = new BigDecimal(orderInfo.getMoney() / 100).setScale(2);
                TSmjOrderInfo qryTSmjOrderInfo = new TSmjOrderInfo();
                qryTSmjOrderInfo.setUserId(userRecipientInfo.getUserId());
                qryTSmjOrderInfo.getParams().put("beginCreateTime", newdateTime);
                qryTSmjOrderInfo.setMachineName(orderInfo.getQrcodeTxt());
                qryTSmjOrderInfo.setHdCode(tSmjGoodList.getGoodHd());
                qryTSmjOrderInfo.setPayAmount(payAmount.toString());
                List<TSmjOrderInfo> tSmjOrderInfoList = itSmjOrderInfoService.selectTSmjOrderInfoListByNoAuth(qryTSmjOrderInfo);
                for (TSmjOrderInfo tSmjOrderInfo1 : tSmjOrderInfoList) {
                    boolean flag = false;
                    if (tSmjOrderInfo1.getPayTime().after(orderInfo.getUpdateTime()) && tSmjOrderInfo1.getPayTime().before(orderInfo.getValidTime())) {
                        logger.info("订单修改时间：{},订单支付时间:{},订单失效时间：{}", sdf.format(orderInfo.getUpdateTime()), tSmjOrderInfo1.getPayTime(), sdf.format(orderInfo.getValidTime()));
                        flag = true;
                    }
                    if(flag){
                        TOrderInfo queryOrder = new TOrderInfo();
                        queryOrder.setChannel(orderInfo.getChannel());
                        queryOrder.setPay3rdOrderNo(tSmjOrderInfo1.getRealChanleOrderNo());
                        String dateTime = new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + " 00:00:00";
                        queryOrder.getParams().put("beginCreateTime", dateTime);
                        List<TOrderInfo> doneTPaymentOrderList = orderService.selectTOrderInfoListByNoAuth(queryOrder);
                        logger.info("渠道订单号是否已经被用：{}", doneTPaymentOrderList.size());
                        if (doneTPaymentOrderList.size() > 0) {
                            continue;
                        }
                        tSmjGoodList.setGoodStatus(0);
                        tSmjGoodList.setGoodNum(tSmjGoodList.getGoodNum() - 1);
                        TSmjGoodList queryTsmj = new TSmjGoodList();
                        queryTsmj.setMachineId(tSmjGoodList.getMachineId());
                        queryTsmj.setSmGoodId(tSmjGoodList.getSmGoodId());
                        if (tSmjGoodList.getPayType().equals("ALI")) {
                            queryTsmj.setPayType("WX");
                        } else {
                            queryTsmj.setPayType("ALI");
                        }
                        List<TSmjGoodList> tmpList = itSmjGoodListService.selectTSmjGoodListListByNoAuth(queryTsmj);
                        TSmjGoodList tmp = null;
                        if (tmpList.size() > 0) {
                            tmp = tmpList.get(0);
                            tmp.setGoodNum(tSmjGoodList.getGoodNum());
                            itSmjGoodListService.updateTSmjGoodList(tmp);
                        }
                        logger.info("商品剩余数量：{}", tSmjGoodList.getGoodNum()-1 );

                        if ((tSmjGoodList.getGoodNum() - 1) < 5) {
                            TSmjMachineList tSmjMachineList = itSmjMachineListService.selectTSmjMachineListById(tSmjGoodList.getMachineId());
                            HashMap<String, String>  requestMap = new HashMap();
                            requestMap.put("id", tSmjMachineList.getSmMachineId());
                            JSONArray jsonArray = new JSONArray();
                            JSONObject obj = new JSONObject();
                            obj.put("id", tSmjGoodList.getSmGoodId());
                            obj.put("huodao", tSmjGoodList.getGoodHd().replace("货道", ""));
                            obj.put("stock", "255");
                            obj.put("price", tSmjGoodList.getGoodPrice().setScale(2));
                            jsonArray.add(obj);
                            requestMap.put("array", jsonArray.toJSONString());
                            String bhUrl = loginUrls[0] + "operator/submitGoodsSetting.action";
                            logger.info("补货参数：{}", JSON.toJSONString(requestMap));
                            HttpResponse bhhttpResponse = HttpUtils.httpFormPost(bhUrl, headerMap, accountObj.getString("cookie"), requestMap, "", "");
                            logger.info("补货返回：{}", bhhttpResponse.getBody());
                            tmp.setGoodNum(255L);
                            itSmjGoodListService.updateTSmjGoodList(tmp);
                            tSmjGoodList.setGoodNum(255L);
                        }
                        itSmjGoodListService.updateTSmjGoodList(tSmjGoodList);
                        tSmjOrderInfo1.setStatus(1);
                        tSmjOrderInfo1.setOrderCode(orderInfo.getId().toString());
                        tSmjOrderInfo1.setMerOrderNo(orderInfo.getOutTradeNo());
                        tSmjOrderInfo1.setCustomOrderNo(orderInfo.getCustomOrderNo());
                        itSmjOrderInfoService.updateTSmjOrderInfo(tSmjOrderInfo1);

                        MsgPayResult msgPayResult = new MsgPayResult();
                        msgPayResult.setChannel(orderInfo.getChannel());
                        msgPayResult.setTradeNo(orderInfo.getId().toString());
                        msgPayResult.setChannelAccount(userRecipientInfo.getChannelAccount());
                        msgPayResult.setOrderId(tSmjOrderInfo1.getRealChanleOrderNo());
                        msgPayResult.setRealMoney(MoneyUtil.fenToYuan(orderInfo.getMoney() + ""));
                        msgPayResult.setUid(userRecipientInfo.getUserId().toString());
                        msgPayResult.setBillTime(sdf.format(tSmjOrderInfo1.getPayTime()));

                        msgPayResult.setChannelPayMsgResult(JSON.toJSONString(tSmjOrderInfo1));
                        ResponseData responseData = chargeService.updateOrderPayResult(false, orderInfo.getId(), msgPayResult, false);
                        chargeService.notifyUserPaySucc(orderInfo.getId());

                        logger.info("售货机订单回调..订单号：" + orderInfo.getId() + " 金额：" + orderInfo.getMoney() + " 处理结果：{}", responseData.getSuccess());
                    }
                }

            }
        }
    }



    public void getSuccOrder() throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        TSmjMachineList query = new TSmjMachineList();
        List<TSmjMachineList> tSmjMachineLists = itSmjMachineListService.selectTSmjMachineListListByNoAuth(query);
        for (TSmjMachineList tSmjMachineList : tSmjMachineLists) {
            TRecipientInfo userRecipientInfo = userRecipientService.selectTRecipientInfoById(tSmjMachineList.getUserRecipientId());

            //出货信息
            HttpResponse deliveryPost = getDeliveryPost(userRecipientInfo,tSmjMachineList);
//            logger.info("机器：{},获取出货订单内容：{}",tSmjMachineList.getMachineName(),deliveryPost.getDocument().select("tbody").first().select("tr").toString());
            Document deliveryPostDoc = deliveryPost.getDocument();
            Element deliveryPageEle = deliveryPostDoc.getElementById("delivery_page");
            String dataTotalcount = deliveryPageEle.attr("data-totalcount");
            logger.info("解析的出货数 {}",dataTotalcount);
            if(redisUtil.get(tSmjMachineList.getMachineCode()+"_delivery_dataTotalcount")==null){
                logger.info("未设置 {} 缓存",tSmjMachineList.getMachineCode()+"_delivery_dataTotalcount");
                Elements lielements = deliveryPostDoc.select("tbody");
                Elements trs = lielements.first().select("tr");
                insertSmjOrderByDelivery(trs,tSmjMachineList,userRecipientInfo);
                redisUtil.set(tSmjMachineList.getMachineCode()+"_delivery_dataTotalcount",dataTotalcount);
                logger.info("设置出货数缓存 {},数量：{}",tSmjMachineList.getMachineCode()+"_delivery_dataTotalcount",dataTotalcount);
            }else{
                logger.info("获取{}缓存数量为：{}，实际解析数量为：{}",tSmjMachineList.getMachineCode()+"_delivery_dataTotalcount",(String)redisUtil.get(tSmjMachineList.getMachineCode()+"_delivery_dataTotalcount"),dataTotalcount);
                if(!dataTotalcount.equals((String)redisUtil.get(tSmjMachineList.getMachineCode()+"_delivery_dataTotalcount"))){
                    deliveryPost = getDeliveryPost(userRecipientInfo,tSmjMachineList);
                    deliveryPostDoc = deliveryPost.getDocument();
                    Elements lielements = deliveryPostDoc.select("tbody");
                    Elements trs = lielements.first().select("tr");
                    insertSmjOrderByDelivery(trs,tSmjMachineList,userRecipientInfo);
                    logger.info("重新设置缓存：{},数量：{}",tSmjMachineList.getMachineCode()+"_delivery_dataTotalcount",dataTotalcount);
                    redisUtil.set(tSmjMachineList.getMachineCode()+"_delivery_dataTotalcount",dataTotalcount);
                }
            }
            //退款
            HttpResponse getRefundGet = getRefundGet(userRecipientInfo,tSmjMachineList);
            Document refundGetDoc = getRefundGet.getDocument();
            Elements refundTbody = refundGetDoc.select("tbody");
            Elements refundTrs = refundTbody.first().select("tr");
//            logger.info("机器：{},获取退款订单内容：{}",tSmjMachineList.getMachineName(),refundTrs.toString());
            insertSmjOrderByRefund(refundTrs,tSmjMachineList,userRecipientInfo);
        }
    }


    private void insertSmjOrderByDelivery(Elements trs,TSmjMachineList tSmjMachineList,TRecipientInfo  userRecipientInfo) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (int i = 0; i < trs.size() - 1; i++) {
            Element tr = trs.get(i);
            Elements cells = tr.select("td");
            String hd = cells.get(1).text();
            String price = cells.get(3).text();
            BigDecimal payAmount = new BigDecimal(price).setScale(2);
            Date payTime = sdf.parse(cells.get(4).text());
            TSmjOrderInfo tSmjOrderInfo = new TSmjOrderInfo();
            tSmjOrderInfo.setHdCode(hd);
            tSmjOrderInfo.setPayAmount(payAmount.toString());
            tSmjOrderInfo.setPayTime(payTime);
            tSmjOrderInfo.setUserId(userRecipientInfo.getUserId());
            tSmjOrderInfo.setRealChanleOrderNo(cells.get(6).text());
            tSmjOrderInfo.setPayType("支付宝");
            List<TSmjOrderInfo> tSmjOrderInfoList = itSmjOrderInfoService.selectTSmjOrderInfoListByNoAuth(tSmjOrderInfo);
            if (tSmjOrderInfoList.size() == 0) {
                tSmjOrderInfo.setMachineName(tSmjMachineList.getMachineName());
                tSmjOrderInfo.setStatus(0);
                itSmjOrderInfoService.insertTSmjOrderInfo(tSmjOrderInfo);
            }
        }
    }


    private HttpResponse getDeliveryPost(TRecipientInfo  userRecipientInfo,TSmjMachineList tSmjMachineList){
        String accountJson = userRecipientInfo.getAccountJson();
        JSONObject accountObj = JSONObject.parseObject(accountJson);
        String[] loginUrls = accountObj.getString("loginUrl").split("login.html");
        HashMap<String, String> headerMap = new HashMap();
        headerMap.put("Cookie", accountObj.getString("cookie"));
        headerMap.put("User-Agent", accountObj.getString("User-Agent"));
        HttpResponse deliveryGet = HttpUtils.httpFormGet(loginUrls[0]+"operator/delivery.html?id="+tSmjMachineList.getSmMachineId(),headerMap,"","");
        String cookies = deliveryGet.getCookie();
        HashMap<String, String> requestMap = new HashMap();
        LocalDate now = LocalDate.now();
        requestMap.put("startTime",now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))+" 00:00:00");
        LocalDate tomorrow = now.plusDays(1);
        requestMap.put("endTime",tomorrow.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))+" 00:00:00");
        requestMap.put("id",tSmjMachineList.getSmMachineId());
        requestMap.put("pageno","");
        HttpResponse deliveryPost =  HttpUtils.httpFormPost(loginUrls[0]+"operator/delivery.html",headerMap,cookies,requestMap,"售货机【盛马】","");
        if(deliveryPost.getBody().contains("登录")){
            userRecipientInfo = reLogin(userRecipientInfo);
            return getDeliveryPost(userRecipientInfo,tSmjMachineList);
        }
        return  deliveryPost;
    }


    private void insertSmjOrderByRefund(Elements trs,TSmjMachineList tSmjMachineList,TRecipientInfo  userRecipientInfo) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (int i = 0; i < trs.size() - 1; i++) {
            Element tr = trs.get(i);
            Elements cells = tr.select("td");
            String hd = cells.get(4).text();
            String price = cells.get(7).text();
            BigDecimal payAmount = new BigDecimal(price).setScale(2);
            Date payTime = sdf.parse(cells.get(10).text());
            TSmjOrderInfo tSmjOrderInfo = new TSmjOrderInfo();
            tSmjOrderInfo.setRealChanleOrderNo(cells.get(1).text());
            tSmjOrderInfo.setMachineName(cells.get(3).text());
            tSmjOrderInfo.setHdCode(hd);
            tSmjOrderInfo.setPayAmount(payAmount.toString());
            tSmjOrderInfo.setPayTime(payTime);
            tSmjOrderInfo.setPayType(cells.get(6).text());
            tSmjOrderInfo.setUserId(userRecipientInfo.getUserId());
            List<TSmjOrderInfo> tSmjOrderInfoList = itSmjOrderInfoService.selectTSmjOrderInfoListByNoAuth(tSmjOrderInfo);
            if (tSmjOrderInfoList.size() == 0) {
                tSmjOrderInfo.setStatus(0);
                itSmjOrderInfoService.insertTSmjOrderInfo(tSmjOrderInfo);
            }
        }
    }


    private HttpResponse getRefundGet(TRecipientInfo  userRecipientInfo,TSmjMachineList tSmjMachineList){
        String accountJson = userRecipientInfo.getAccountJson();
        JSONObject accountObj = JSONObject.parseObject(accountJson);
        String[] loginUrls = accountObj.getString("loginUrl").split("login.html");
        HashMap<String, String> headerMap = new HashMap();
        headerMap.put("Cookie", accountObj.getString("cookie"));
        headerMap.put("User-Agent", accountObj.getString("User-Agent"));
        HttpResponse deliveryGet = HttpUtils.httpFormGet(loginUrls[0]+"operator/refund.html",headerMap,"","");
        if(deliveryGet.getBody().contains("登录")){
            userRecipientInfo = reLogin(userRecipientInfo);
            return getRefundGet(userRecipientInfo,tSmjMachineList);
        }
        return  deliveryGet;
    }

}
